import models.posts
# To change this template, choose Tools | Templates
# and open the template in the editor.
import web
import models

__author__="yangqibin"
__date__ ="$Nov 12, 2011 7:51:42 PM$"

t_globals = { 'datestr':web.datestr }

render = web.template.render('templates', base='posts_base', globals=t_globals)

class Index:
    def GET(self):
        posts = models.posts.get_posts()
        return render.index(posts)

class View:
    def GET(self, id):
        post = models.posts.get_post(int(id))
        return render.view(post)

class New:
    form = web.form.Form(
      web.form.Textbox("title", web.form.notnull, size=30, description="Post title:"),
      web.form.Textarea("content", web.form.notnull, rows=30, cols=80, description="Post content:"),
      web.form.Button('Post entry')
    )

    def GET(self):
        form = self.form()
        return render.new(form)

    def POST(self):
        form = self.form()
        if not form.validates():
            return render.new(form)
        models.posts.new_post(form.d.title, form.d.content)
        raise web.seeother('/index')

class Delete:
    def GET(self, id):
        models.posts.del_post(int(id))
        raise web.seeother('/index')

    def POST(self, id):
        models.posts.del_post(int(id))
        raise web.seeother('/index')

class Edit:
    def GET(self, id):
        post = models.posts.get_post(int(id))
        form = New.form()
        form.fill(post)
        return render.edit(post, form)

    def POST(self, id):
        form = New.form()
        post = models.posts.get_post(int(id))
        if not form.validates():
          return render.edit(post, form)
        models.posts.update_post(int(id), form.d.title, form.d.content)
        raise web.seeother('/index')

if __name__ == "__main__":
    print "Hello World"
